/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tfb.service.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtil {

    private static final Logger log = Logger.getLogger(JsonUtil.class);
    public static final String          UTF8   = "UTF-8";
    private static final ObjectMapper   mapper = new ObjectMapper(); // can
                                                                     // reuse,
                                                                     // share
                                                                     // globally
    private final JsonGenerator         json;
    private final ByteArrayOutputStream baos;

    public JsonUtil(JsonGenerator json, ByteArrayOutputStream baos) {
        this.json = json;
        this.baos = baos;
    }

    public static <T extends Object> T readValue(String content, Class<T> clazz) throws IOException {
        return mapper.readValue(content, clazz);
    }

    public static String writeValue(Object value) {
        try {
            return mapper.writeValueAsString(value);
        } catch (IOException ex) {
            return ex.fillInStackTrace().getMessage();
        }
    }

    public JsonGenerator getGenerator() {
        return this.json;
    }

    public ByteArrayOutputStream getByteArrayOutputStream() {
        return this.baos;
    }

    public String toUTF8String() throws IOException {
        this.json.flush();
        return this.baos.toString("UTF-8");
    }

    public static JsonUtil createJsonUtility() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JsonGenerator json = JsonUtil.createJsonGenerator(baos);
        return new JsonUtil(json, baos);
    }

    public static JsonGenerator createJsonGenerator(OutputStream out) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.getJsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static JsonNode createJson(String jsonText) {
        try {
            ObjectMapper om = new ObjectMapper();
            return om.readTree(jsonText);
        } catch (Exception ex) {
            log.error(jsonText);
            throw new RuntimeException(ex);
        }
    }

    public static boolean isNotNull(JsonNode json) {
        return json != null && !json.isNull();
    }

    public static boolean isNull(JsonNode json) {
        return json == null || json.isNull();
    }
}
